{% extends 'base.html' %}
{% load staticfiles %}

{% block head %}
    <link rel="stylesheet" href="{% static 'css/selectize.css' %}">
    <link href="{% static 'bootstrap-table/css/bootstrap-table.min.css' %}" rel="stylesheet">
    <link rel="stylesheet" href="{% static 'css/bootstrap-datepicker.min.css' %}">
    <link rel="stylesheet" href="{% static 'bootstrap-duallistbox/bootstrap-duallistbox.min.css' %}">

<style>
    .agile_info_panel {
        min-height: 800px;
    }

    .bootstrap-table>.fixed-table-toolbar>.columns {
        margin-bottom: 10px;
    }

    .bootstrap-table>.fixed-table-toolbar>.pull-right.search {
        margin-top: -3px;
        margin-right: 5px;
    }

    table tbody tr td, .form-static-text{
        word-wrap: break-word;
        word-break: break-all;
    }

    .table-text {
        max-height: 60px;
        word-wrap: break-word;
        word-break: break-all;
        overflow:hidden;
    }

    .id-width {
        width:50px;
    }

    .checkbox-width {
        width:35px;
    }

    .btn.clear1.pull-right.btn-default.btn-xs, .btn.clear2.pull-right.btn-default.btn-xs{
        padding:0 7px 0 7px !important;
        font-size: 13px;
        margin-top: 2px;
    }
</style>

{% endblock %}

{% block breadcrumb %}
    <h1>快速新增</h1>
    <ol class="breadcrumb">
        <li><a href="javascript:void(0);"><i class="fa fa-dashboard"></i> 仪表盘</a></li>
        <li><a href="javascript:void(0);"> 项目管理</a></li>
        <li><a href="javascript:void(0);"> 上线单统计</a></li>
    </ol>
{% endblock %}

{% block content %}
    <div class="row">
         <div class="col-md-12 col-xs-12" style="border-color: #c7c7c7; border-width: 0 0 1px 0; border-style: solid; margin-bottom: 5px;margin-top: 5px;">
             <div class="col-md-12 col-xs-12">
                <label class="control-label" style="float: left; width: 100px;">上线系统：</label>
                <div class="input-group col-xs-11">
                  <select multiple="multiple" size="10" id="systemlist" name="system_form">
                      {% for s in system %}
                        <option value="{{s.id}}">{{s.product_name}}</option>
                      {% endfor %}
                  </select>
                </div>
            </div>

             <div class="form-group col-md-8" style="margin-bottom: -5px;">
                 <label class="control-label" style="float: left; width: 100px;">上线日期：</label>
                 <div class="input-group col-xs-9">
                    <input type="text" class="input-sm form-control" name="product_date_start" id="id_product_date_group_start" placeholder="开始时间"/>
                    <span class="input-group-addon">to</span>
                    <input type="text" class="input-sm form-control" name="product_date_end" id="id_product_date_group_end" placeholder="结束时间"/>
                 </div>
             </div>

             <div class="col-md-2 col-xs-12" style="float: right; margin-top: 3px; margin-bottom: 5px;">
                 <a onclick="javascript:if(timeDifference()){$('#inventory-statistic-table').bootstrapTable('refresh')};" id="searchall" class="btn btn-primary btn-sm" style="float: right; width: 100%; padding-top: 5px; padding-bottom: 5px;"><i class="fa fa-search"></i>查 询</a>
             </div>
         </div>

        <div id="inventory-statistic">
            <div class="col-md-6">
                <div id="toolbar">
                    <!--span style="font-size: 12px; color: #777777;">注: 本表格统计系统在指定时间内投产的上线单与该时段内对应的二次变更数.</span-->
                    <span style="font-size: 12px; color: #777777;">注: 本表格统计系统在指定时间内投产的上线单与对应的所有历史二次变更数.</span>
                </div>
            </div>
            <div class="col-md-12">
                <table id="inventory-statistic-table"></table>
            </div>
        </div>

        <div class="col-md-12" style="margin-top: 15px; border-top-style: solid; border-width: 1px; border-color: #c7c7c7;">
            <div class="panel">
                <div class="panel-title" style="margin-top: 13px; color: #525252; font-size: 17px; text-align: center;">
                    最近12周 汇总图
                </div>
                <div class="panel-body">
                    <div id="main-chart" style="height: 500px; overflow: auto;"></div>
                </div>
            </div>
        </div>
    </div>

{% endblock %}
{% block js %}
    <script src="{% static 'js/selectize.min.js' %}"></script>
    <script src="{% static 'js/bootbox.js' %}"></script>
    <script src="{% static 'bootstrap-duallistbox/jquery.bootstrap-duallistbox.min.js' %}"></script>
    <script src="{% static 'js/echarts.min.js' %}"></script>
    <script src="{% static 'js/macarons.js' %}"></script>
    <script src="{% static 'js/bootstrap-datepicker.min.js' %}"></script>
    <script src="{% static 'js/bootstrap-datepicker.zh-CN.min.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/bootstrap-table.min.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/bootstrap-table-editable.min.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/bootstrap-table-filter-control.min.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/bootstrap-table-multiple-sort.min.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/bootstrap-table-multiple-sort-zh-CN.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/tableExport.min.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/bootstrap-table-zh-CN.min.js' %}"></script>

    <script>
            var init_search = function(){
                var init_date = new Date()
                var day = init_date.getDay() || 7
                var monday = new Date(init_date.getFullYear(), init_date.getMonth(), init_date.getDate() + 1 - day)
                var sunday = new Date(init_date.getFullYear(), init_date.getMonth(), init_date.getDate() + 7 - day)

                $('#id_product_date_group_start').datepicker({
                    format: "yyyy-mm-dd",
                    clearBtn: true,
                    language: "zh-CN",
                    autoclose: true,
                    todayHighlight: true,
                })
                $('#id_product_date_group_end').datepicker({
                    format: "yyyy-mm-dd",
                    clearBtn: true,
                    language: "zh-CN",
                    autoclose: true,
                    todayHighlight: true
                })
                $('#id_product_date_group_start').datepicker('setDate',monday)
                $('#id_product_date_group_end').datepicker('setDate',sunday)

                $('#id_delay').selectize()
            }

            init_search()

            var queryParams = function (params) {
                var setup = {}
                $('#id_product_date_group_start,#id_product_date_group_end').each(function(i){
                    el = $(this)
                    if(el.val()){
                        setup[el.attr('name')]=el.val()
                    }
                })
                setup.system = $('#systemlist[name="system_form"]').val()
                var param = {
                    setup: JSON.stringify(setup),
                }
                return param
            }

            var responseHandler = function (e) {
                if (e.total > 0) {
                  return { "rows": e.rows, "total": e.total }
                }
                else {
                  return { "rows": [], "total": 0 }
                }
            }
            
            var default_range = function(dt, type){
                    var date = new Date(dt);
                    type=='1'?date.setDate(date.getDate() + 30):date.setDate(date.getDate() - 30)
                    return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate()
                }

            var timeDifference = function (){
                var start = $('#id_product_date_group_start').val()
                var end = $('#id_product_date_group_end').val()
                if(!start&&!end){
                    bootbox.alert('请选择提单日期范围!')
                    return false
                }
                if(!start){
                    $('#id_product_date_group_start').datepicker('setDate',default_range(end,0))
                    return true
                }
                if(!end){
                    $('#id_product_date_group_end').datepicker('setDate',default_range(start,1))
                    return true
                }
                var date = new Date(end).getTime() - new Date(start).getTime()   //时间差的毫秒数
                if(date<0){
                    bootbox.alert('开始时间不能大于结束时间')
                    return false
                }
                var days=Math.floor(date/(24*3600*1000))
                if(days>365){
                    bootbox.alert('搜索范围不能超过365天!')
                    return false
                }
                return true
            }

            function totalFormatter(data) {
                var field = this.field
                return data.map(function (row) {
                  return row[field]
                }).reduce(function (sum, i) {
                  return sum + i
                }, 0)
            }

            echarts.registerTheme('macarons', macarons())
            var myChart = echarts.init(document.getElementById('main-chart'),'macarons')
            var option = {
                title: {
                    subtext: '注: 该图以一周为间隔,统计最近12周投产\n的上线单与对应的所有历史二次变更.',
                    textAlign: 'left',
                    padding: [0,0,5,0],
                    top: -5,
                },
                tooltip : {
                    trigger: 'axis'
                },
                toolbox: {
                    show : true,
                    feature : {
                        mark : {show: true},
                        dataView : {show: true, readOnly: false},
                        magicType: {show: true, type: ['line', 'bar']},
                        restore : {show: true},
                        saveAsImage : {show: true}
                    }
                },
                calculable : true,
                legend: {
                    data:['上线单合计','二次变更合计']
                },
                xAxis : [
                    {
                        type : 'category',
                        data : ['-11 周','-10 周','-9 周','-8 周','-7 周','-6 周','-5 周','-4 周','-3 周','-2 周','-1 周','本周']
                    }
                ],
                yAxis : [
                    {
                        type : 'value',
                        name : '上线单',
                        minInterval: 1,
                        axisLabel : {
                            formatter: '{value} 个'
                        }
                    },
                    {
                        type : 'value',
                        name : '二次变更',
                        minInterval: 1,
                        axisLabel : {
                            formatter: '{value} 次'
                        }
                    }
                ],
                series : [
                    {
                        name:'上线单合计',
                        type:'bar',
                        data:[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                        markPoint : {
                            data : [
                                {type : 'max', name: '最大值'},
                                {type : 'min', name: '最小值'}
                            ]
                        },
                        markLine : {
                            data : [
                                {type : 'average', name: '平均值'}
                            ]
                        },
                    },
                    {
                        name:'二次变更合计',
                        type:'line',
                        yAxisIndex: 1,
                        data:[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                        markPoint : {
                            data : [
                                {type : 'max', name: '最大值'},
                                {type : 'min', name: '最小值'}
                            ]
                        },
                        markLine : {
                            data : [
                                {type : 'average', name: '平均值'}
                            ]
                        },
                    }
                ]
            }

            var tableInit = function (name) {
              $('#inventory-statistic-table').empty()
              $('#inventory-statistic-table').bootstrapTable('destroy').bootstrapTable({
                  url: '/project/inventorystatisticinfo/',   //url一般是请求后台的url地址,调用ajax获取数据。此处我用本地的json数据来填充表格。
                  method: "get",                     //使用get请求到服务器获取数据
                  dataType: "json",
                  contentType: 'application/json,charset=utf-8',
                  uniqueId: "system_id",                    //每一行的唯一标识，一般为主键列
                  cache: false,                       // 不缓存
                  toolbar: "#toolbar",
                  classes: "table table-bordered table-hover table-striped",
                  queryParamsType: "limit",           //设置为"undefined",可以获取pageNumber，pageSize，searchText，sortName，sortOrder
                                                      //设置为"limit",符合 RESTFul 格式的参数,可以获取limit, offset, search, sort, order
                  queryParams: queryParams,
                  sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
                  sortable: true,                     //是否启用排序,意味着整个表格都会排序
                  pagination: true,                   //是否显示分页（*）
                  search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
                  showColumns: true,                  //是否显示所有的列
                  showRefresh: true,                  //是否显示刷新按钮
                  showToggle: true,                    //是否显示详细视图和列表视图
                  clickToSelect: true,                //是否启用点击选中行
                  minimumCountColumns: 3,          //最少允许的列数 clickToSelect: true, //是否启用点击选中行
                  pageNumber: 1,                   //初始化加载第一页，默认第一页
                  pageSize: 10,                    //每页的记录行数（*）
                  pageList: [10,20,50,100,'所有'],     //可供选择的每页的行数（*）
                  paginationPreText: "上一页",
                  paginationNextText: "下一页",
                  showFooter: true,
                  filterControl: true,
                  filterShowClear: true,
                  showMultiSort: true,
                  responseHandler: responseHandler,
                  showExport: true,
                  exportDataType: 'selected',
                  exportTypes: ['json', 'xml', 'csv', 'txt', 'sql', 'excel',],
                  exportOptions: {
                    ignoreColumn: [],
                    mso: {
                        worksheetName: '上线单统计表',
                    },
                    onCellHtmlData: function (cell, rowIndex, colIndex, htmlData) {
                      if (cell.is('th')) {
                        return cell.find('.th-inner').text()
                      }
                      return htmlData
                    },
                  },
                  columns: [
                            {
                                checkbox: true,
                                class: 'checkbox-center-middle cell-ignore',
                                align: 'center',
                                class: 'checkbox-width',
                                valign: 'middle',
                            }, {
                                title: '编号',
                                field: 'system_id',
                                align: 'center',
                                valign: 'middle',
                                class: 'id-width',
                                width: 50,
                                footerFormatter: function(){return '-'},
                            }, {
                                title: '系统',
                                field: 'system',
                                align: 'center',
                                valign: 'middle',
                                filterControl: 'input',
                                sortable:true,
                                footerFormatter: function(){return '上线单合计'},
                            }, {
                                title: '正常单数量',
                                field: 'formal',
                                align: 'center',
                                sortable:true,
                                valign: 'middle',
                                footerFormatter: totalFormatter,
                            }, {
                                title: '紧急单数量',
                                field: 'emergency',
                                align: 'center',
                                sortable:true,
                                valign: 'middle',
                                footerFormatter: totalFormatter,
                            }, {
                                title: '灵活单数量',
                                field: 'flexible',
                                align: 'center',
                                sortable:true,
                                valign: 'middle',
                                footerFormatter: totalFormatter,
                            }, {
                                title: '上线单合计',
                                field: 'total',
                                align: 'center',
                                sortable:true,
                                valign: 'middle',
                                footerFormatter: totalFormatter,
                            }, {
                                title: '二次变更次数',
                                field: 'change',
                                align: 'center',
                                sortable:true,
                                valign: 'middle',
                                footerFormatter: totalFormatter,
                            },
                      ],
                  onLoadSuccess: function (data) { //加载成功时执行
                      $.ajax({
                        type: "post",
                        url: "/project/getrecentinventory/",
                        headers: {"X-CSRFtoken": '{{ csrf_token }}'},
                        data: JSON.stringify({
                                system: $('#systemlist[name="system_form"]').val(),
                            }),
                        success: function (data){
                            res = data.reverse()
                            option.series[0].data=[]
                            option.series[1].data=[]
                            for(i in res){
                                option.series[0].data.push(res[i].inventory_count)
                                option.series[1].data.push(res[i].changes_count)
                            }
                            myChart.setOption(option)
                        }
                    })
                  },
                  onLoadError: function (res) { //加载失败时执行
                      console.log(res)
                  },
              });
            }

            tableInit()

            var systemSelect = $('#systemlist[name="system_form"]').bootstrapDualListbox({
                filterPlaceHolder: "请选择系统",
                filterTextClear: '还原',
                infoTextFiltered: '共找到{0}个',
                infoText: "共计 {0}",
                infoTextEmpty: "无",
            });

    </script>
{% endblock %}
